import { login } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import md5 from 'js-md5'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    sessionStorage.clear()
    const { username, password, loginType } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username, passwd: md5(password), loginType: loginType }).then(response => {
        const { data } = response
        sessionStorage.setItem('userInfo', JSON.stringify(data))
        var authType = ''
        let type = ''
        if (loginType === '2') {
          if (data.rootType === 0) {
            authType = 'nomalAuth'
            type = 1
          } else {
            authType = 'root'
            type = ''
          }
        } else {
          authType = 'staff'
          if (data.isManager) {
            authType += 'Manager'
            type = 3
          }
          type = 2
          if (data.isKnowPro) {
            authType += 'KnowPro'
          }
          if (data.isArch) {
            authType += 'Arch'
          }
        }
        sessionStorage.setItem('authType', authType)
        sessionStorage.setItem('type', type)
        sessionStorage.setItem('menu', JSON.stringify(data.res))
        setToken(authType)
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    commit('SET_NAME', '您好')
    var temp_roles = JSON.parse(sessionStorage.getItem('menu'))
    commit('SET_ROLES', temp_roles)
    return { roles: temp_roles }
  },

  // user logout
  logout({ commit, state, dispatch }) {
    dispatch('tagsView/delAllViews', null, { root: true })
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
    removeToken()
    resetRouter()
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
